package net.csdn.business.common.oauth2.service.impl;

import cn.authing.core.types.User;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.csdn.business.common.constant.RedisConstants;
import net.csdn.business.common.domain.request.oauth.*;
import net.csdn.business.common.domain.vo.oauth.OauthClientInfoVo;
import net.csdn.business.common.domain.vo.oauth.OauthStatVO;
import net.csdn.business.common.domain.vo.oauth.StatClientAuthVO;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.exception.BusinessException;
import net.csdn.business.common.oauth2.mapper.OauthClientInfoMapper;
import net.csdn.business.common.oauth2.model.entity.OauthClientInfo;
import net.csdn.business.common.oauth2.service.IOauthAccessTokenService;
import net.csdn.business.common.oauth2.service.IOauthClientInfoService;
import net.csdn.business.common.oauth2.service.IStatClientAuthService;
import net.csdn.business.common.service.SnowflakeService;
import net.csdn.business.common.service.SuperServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * oauth应用管理Service业务层处理
 * 
 * @author zhangyl
 * @date 2022-11-07
 */
@Service
public class OauthClientInfoServiceImpl extends SuperServiceImpl<OauthClientInfoMapper, OauthClientInfo> implements IOauthClientInfoService
{


    @Autowired
    private SnowflakeService snowflakeService;

    @Autowired
    private IOauthAccessTokenService oauthAccessTokenService;

    @Autowired
    private IStatClientAuthService statClientAuthService;



    /**
     * 分页我创建的oauth应用列表
     *
     * @param query oauth应用管理详细信息
     * @return oauth应用管理
     */
    @Override
    public Page<OauthClientInfoVo> findPageList(OauthClientInfoQuery query) {
        //获得Page对象
        Page<OauthClientInfoVo> page = query.getPage();
        List<OauthClientInfoVo> pageList=baseMapper.findPageList(page,query);
        if(pageList!=null&&pageList.size()>0){
            pageList.stream().forEach(oauthClientInfoVo->{
                String clientSecret=oauthClientInfoVo.getClientSecret();
                if(StringUtils.isNotBlank(clientSecret)){
                    clientSecret = DesensitizedUtil.password(clientSecret);
                    oauthClientInfoVo.setClientSecret(clientSecret);
                }
            });
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 分页查询已授权的oauth应用列表
     *
     * @param query oauth应用管理详细信息
     * @return oauth应用管理
     */
    @Override
    public Page<OauthClientInfoVo> findAuthorizeList(OauthClientInfoQuery query) {
        //获得Page对象
        Page<OauthClientInfoVo> page = query.getPage();
        List<OauthClientInfoVo> pageList=baseMapper.findAuthorizeList(page,query);
        if(pageList!=null&&pageList.size()>0){
            List<String> usedIds=new ArrayList<>();
            pageList.stream().forEach(oauthClientInfoVo->{
                String clientSecret=oauthClientInfoVo.getClientSecret();
                if(StringUtils.isNotBlank(clientSecret)){
                    clientSecret = DesensitizedUtil.password(clientSecret);
                    oauthClientInfoVo.setClientSecret(clientSecret);
                }
                String creatreBy=oauthClientInfoVo.getCreatedBy();
                if(StringUtils.isNotBlank(creatreBy)){
                    usedIds.add(creatreBy);
                }
            });
            //批量查询创建人信息
            Map<String, User>  userInfos=null;
            try {
                //userInfos=authingService.queryUserByIdsToMap(usedIds);
            }catch (Exception e){
                 e.printStackTrace();
            }
            if(userInfos!=null&&userInfos.size()>0){
                for (OauthClientInfoVo oauthClientInfoVo:pageList) {
                    String creatreBy=oauthClientInfoVo.getCreatedBy();
                    User user=userInfos.get(creatreBy);
                    oauthClientInfoVo.setCreatedByName(user==null?"":user.getUsername());
                }
            }
        }
        page.setRecords(pageList);
        return page;
    }

    /**
     * 根据id查询oauth应用管理
     *
     * @param id oauth应用管理主键
     * @return oauth应用管理
     */
    @Override
    public OauthClientInfoVo selectOauthClientInfoById(String id)
    {
        OauthClientInfoVo result=null;
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getObjectId, id);
        OauthClientInfo oauthClientInfo=baseMapper.selectOne(queryWrapper);
        if(oauthClientInfo!=null){
            result=new OauthClientInfoVo();
            BeanUtils.copyProperties(oauthClientInfo, result);
        }
        return result;
    }

    /**
     * 根据id查询oauth应用管理
     * 
     * @param clientId oauth应用clientId
     * @param isWithSecret 是否返回clientSecret，true：返回；false;脱敏
     * @return oauth应用管理
     */
    @Override
    public OauthClientInfoVo selectClientByClientId(String clientId,Boolean isWithSecret){
        OauthClientInfoVo result=null;
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getClientId, clientId);
        OauthClientInfo oauthClientInfo=baseMapper.selectOne(queryWrapper);
        if(oauthClientInfo!=null){
            result=new OauthClientInfoVo();
            BeanUtils.copyProperties(oauthClientInfo, result);
            String userName=null;
            //查询应用创建人的名称
            String creatreBy=oauthClientInfo.getCreatedBy();
            try {
                //User user= authingService.getUserById(creatreBy);
                User user=null;
                userName=user==null?"":user.getUsername();
            }catch (Exception e){
              e.printStackTrace();
            }
            result.setCreatedByName(userName);
            //处理clientSecret,全部返回*
            String clientSecret=oauthClientInfo.getClientSecret();
            if(!isWithSecret&&StringUtils.isNotBlank(clientSecret)){
                clientSecret = DesensitizedUtil.password(clientSecret);
                result.setClientSecret(clientSecret);
            }
        }
        return result;
    }

    /**
     * 查询oauth应用管理列表
     * 
     * @param query oauth应用管理
     * @return oauth应用管理
     */
    @Override
    public List<OauthClientInfoVo> selectOauthClientInfoList(OauthClientInfoQuery query)
    {
        return baseMapper.selectOauthClientInfoList(query);
    }

    /**
     * 新增oauth应用管理
     * 
     * @param newOauthClientInfoDTO oauth应用管理
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertOauthClientInfo(NewOauthClientInfoDTO newOauthClientInfoDTO)
    {
        OauthClientInfo oauthClientInfo=new OauthClientInfo();
        BeanUtils.copyProperties(newOauthClientInfoDTO,oauthClientInfo);
        oauthClientInfo.setObjectId(snowflakeService.nextNo());
        oauthClientInfo.setCreatedBy(newOauthClientInfoDTO.getCreatedBy());
        String clientId=null;
        OauthClientInfo oauthClient=null;
        //如果client存在就重新生成。
        do{
            clientId= RandomUtil.randomString(64);
            //验证当前clientId是否存在，防止生成重复
            LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
            queryWrapper.eq(OauthClientInfo::getClientId, clientId);
            oauthClient=baseMapper.selectOne(queryWrapper);
        }while (oauthClient!=null);
        oauthClientInfo.setClientId(clientId);
        String clientSecret=RandomUtil.randomString(64);
        oauthClientInfo.setClientSecret(clientSecret);
        oauthClientInfo.setScope("read:user");
        oauthClientInfo.setAuthorizedGrantTypes("password,authorization_code,refresh_token");
        oauthClientInfo.setCreatedDate(new Date());
        baseMapper.insert(oauthClientInfo);
        return oauthClientInfo.getClientId();
    }

    @Override
    @CacheEvict(value = RedisConstants.OAUTH2_CLIENT_INFO, key = "#params.clientId")
    public String generateSecret(NewOauthClientSecretDTO params) {
        String clientId=params.getClientId();
        //查询clint是否存在
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getClientId, clientId);
        OauthClientInfo oauthClientInfo=baseMapper.selectOne(queryWrapper);
        if(oauthClientInfo==null){
            throw new BusinessException(ResultCodeEnum.OAUTH_CLIENT_ID_ERROR);
        }
        String clientSecret=RandomUtil.randomString(64);
        LambdaUpdateWrapper<OauthClientInfo> updateWrapper = new UpdateWrapper<OauthClientInfo>().lambda();
        updateWrapper.eq(OauthClientInfo::getClientId, clientId);
        oauthClientInfo.setClientSecret(clientSecret);
        oauthClientInfo.setLastModifiedBy(params.getLastModifiedBy());
        oauthClientInfo.setLastModifiedDate(new Date());
        baseMapper.update(oauthClientInfo,updateWrapper);
        return clientSecret;
    }


    /**
     * 修改oauth应用管理
     * 
     * @param params oauth应用管理
     * @return 结果
     */
    @Override
    @CacheEvict(value = RedisConstants.OAUTH2_CLIENT_INFO, key = "#params.clientId")
    public Integer updateOauthClientInfo(UpdateOauthClientInfoDTO params)
    {
        String clientId=params.getClientId();
        //查询clint是否存在
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getClientId, clientId);
        OauthClientInfo oauthClientInfo=baseMapper.selectOne(queryWrapper);
        if(oauthClientInfo==null){
            throw new BusinessException(ResultCodeEnum.OAUTH_CLIENT_ID_ERROR);
        }
        LambdaUpdateWrapper<OauthClientInfo> updateWrapper = new UpdateWrapper<OauthClientInfo>().lambda();
        updateWrapper.eq(OauthClientInfo::getClientId, clientId);
        BeanUtils.copyProperties(params,oauthClientInfo);
        oauthClientInfo.setLastModifiedBy(params.getLastModifiedBy());
        oauthClientInfo.setLastModifiedDate(new Date());
        return baseMapper.update(oauthClientInfo,updateWrapper);
    }

    /**
     * 删除oauth应用管理信息
     * 
     * @param clientId oauth应用clientId
     * @return 结果
     */
    @Override
    @CacheEvict(value = RedisConstants.OAUTH2_CLIENT_INFO, key = "#clientId")
    public Integer deleteByClientId(String clientId)
    {
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getClientId, clientId);
        return baseMapper.delete(queryWrapper);
    }


    @Override
    public OauthStatVO authStat(String clientId)
    {
        OauthStatVO result=new OauthStatVO();
        StatClientAuthQuery query=new StatClientAuthQuery();
        query.setClientId(clientId);
        query.setStatDate(DateUtil.today());
        List<StatClientAuthVO> authNumOfWeek=statClientAuthService.selectStatClientAuthList(query);
        result.setAuthNumOfWeek(authNumOfWeek);
        Integer authUserTotal= oauthAccessTokenService.findAuthUserNum(clientId);
        result.setAuthUserTotal(authUserTotal==null?0:authUserTotal);
        return result;
    }

    /*@Override
    public OauthClientInfoVo getClientByClientId(String clientId) {
        OauthClientInfoVo result=null;
        LambdaQueryWrapper<OauthClientInfo> queryWrapper = new QueryWrapper<OauthClientInfo>().lambda();
        queryWrapper.eq(OauthClientInfo::getClientId, clientId);
        OauthClientInfo oauthClientInfo=baseMapper.selectOne(queryWrapper);
        if(oauthClientInfo!=null){
            result=new OauthClientInfoVo();
            BeanUtils.copyProperties(oauthClientInfo, result);
        }
        return result;
    }*/
}
